/*
 * @Author       : xh
 * @Date         : 2022-11-14 19:53:18
 * @LastEditors: y001554
 * @FileName     :
 */
import {
  defineComponent,
  toRefs,
  reactive,
  computed,
  onMounted,
  watch,
  isProxy,
  ref,
  onUnmounted,
  isRef
} from 'vue'
import {  ElTable } from 'element-plus'
import { CUSTOMER_PROPS, IPROPS,  } from './composables/setting'
import useSelect from  './composables/use-select'
// import { More, ArrowDown } from '@element-plus/icons-vue'
import {
  Items,
  componentProps,
  ComponentProps,
  ItemData,
  ActionsItems  
} from './type'
import './index.scss'
import { deepMerge } from '../../../utils'

export default defineComponent({
  name: 'M-Table',
  props: componentProps,
  emits: ['update:modelValue','scrollTop'],
  setup(props: ComponentProps, context) {
    const { slots, emit, attrs,expose } = context
    const {extra } = toRefs(props)
    let { customerProps, tableModal, actionsModal,request, } = props
    const domRef = ref<InstanceType<typeof ElTable>>()
    const loading = ref<boolean>(false)

    const  tableBodyDom = ref<any>(null)
    const  {all, selectFn,clearFn,allFn}  =  useSelect(context,domRef)
    const tableData = ref<Array<any>>([])
    const count = ref<number>(0)
    const  pagination =  reactive({size:10,page:1 })



   customerProps = deepMerge(CUSTOMER_PROPS, customerProps)
 

    //@注释
    //@name:渲染节点
    //@params:
    //@des:
    const renderLeftColumns = () => {
      return (
        <>
          {customerProps.showExpand && <el-table-column type="expand" fixed />}

          {customerProps.showCheck && (
            <el-table-column type="selection" fixed  reserve-selection/>
          )}
          {customerProps.showIndex && (
            <el-table-column label="序号" width="60" type="index" fixed />
          )}
        </>
      )
    }
    const renderColumns = () => {
      return tableModal.map((item: Items, index: number) => {
        let canshow = item.permission ? item.permission() : true

        return canshow ? (
          <el-table-column {...item.iProps} reserve-selection label={item.label} prop={item.prop}>
            {slots[item.prop]
              ? slots[item.prop]!(item)
              : item.renderText
              ? item.renderText()
              : null}
          </el-table-column>
        ) : null
      })
    }
    const filterRightActions = (arr: any): any => {
      let res: any = {
        showList: [],
        collapseList: []
      }

      if (arr && arr.length) {
        arr.map((it: any) => {
          if (it.inCollapse) {
            res.collapseList.push(it)
          } else {
            res.showList.push(it)
          }
        })
      } else {
        res = null
      }

      return res
    }
    const renderRightActions = () => {
      const arr = actionsModal.filter((it: ActionsItems) => {
        if (it.permission) {
          const type = typeof it.permission
          if (type === 'function') {
            return it.permission()
          } else if (type === 'string') {
            return true
          } else {
            return true
          }
        } else {
          return true
        }
      })
      const actions = filterRightActions(arr)
      return (
        actions && (
          <el-table-column
            label="操作"
            fixed="right" 
            width={arr.length *  76}
          >
            {actions.showList.length &&
              actions.showList.map((it: any) => {
                return (
                  <el-button
                    size={attrs.size || 'small'}
                    type={it.type || 'default'}
                    onClick={() => it.onclick(it)}
                  >
                    {it.label}
                  </el-button>
                )
              })}
            {actions.collapseList.length &&
              renderCollapseBtns(actions.collapseList)}
          </el-table-column>
        )
      )
    }

    const renderCollapseBtns = (collapseList: any) => {
      const subs = () => {
        return (
          <el-dropdown-menu>
            {collapseList.map((it: any) => (
              <el-dropdown-item onClick={() => it.onclick(it)}>
                {it.label}
              </el-dropdown-item>
            ))}
          </el-dropdown-menu>
        )
      }
      return (
        <el-dropdown
          v-slots={{
            dropdown: subs,
            default: () => (
              <el-button
                style="margin-left:10px"
                size={attrs.size || 'small'}
                type="text"
              >
                更多
              </el-button>
            )
          }}
          placement="bottom"
        ></el-dropdown>
      )
    }



    //@注释
    //@name:数据加载
    //@params:
    //@des:
    const beParams = (data:any):any=>{

      // console.log('key',data)
      for (const key in data) {
        if(isProxy(data[key])){
          data[key] =  JSON.parse(JSON.stringify(data[key]))
         } 
        
         if(!data[key]){
          delete  data[key]
         }  
         
      }
      return data
    }

    const loadList=async ( ):Promise<void> => {
      if(!request)return 
      loading.value =  true
      const params =  beParams( { ...pagination,...extra.value})
      // console.log('params111',params)


      // debugger
      try {
        const  res = await request(params)
        tableData.value = res.list
        count.value = res.count
      } catch (error) {
        console.error('error',error)
      }
      loading.value =  false
    }

 
    //@注释
    //@name:  像外暴露函数
    //@params:
    //@des:
    const refresh = (): void => {
      loadList()
    }
    const reset = (): void => {
      pagination.size=10
      pagination.page = 1
      loadList()
    }
    const cancel = (): void => {}



    //@注释
    //@name:
    //@params:初试话滚轮监听
    //@des:
    const initScroll =  ()=>{
      //  debugger
       let scrollTop = tableBodyDom.value.scrollTop

      // console.log('scrollTop', scrollTop)
      emit('scrollTop', scrollTop)
    }

    onMounted(async () => {
      // console.log(222, props)
      if(!customerProps.manualLoad){
        //是否自动触发
          loadList()
      } 
      const dom:any  = domRef.value?.$refs?.bodyWrapper
      // console.log('dom',dom)

      if(!customerProps.scrollListen)return 

      const selectwrap = dom.querySelector('.el-scrollbar__wrap')
      // console.log('selectwrap',selectwrap)
      selectwrap && (tableBodyDom.value = selectwrap)
        // console.log('deomRf.value',dom)
        try {
          selectwrap &&  selectwrap.addEventListener('scroll',initScroll)

        } catch (error) {
          console.log('error',error)
        } 
    })

    onUnmounted(()=>{
      tableBodyDom.value && tableBodyDom.value.removeEventListener('scroll',initScroll)
      console.log('取消监听'  )
  })
    watch(
      () => pagination,
      (v) => {
        loadList()
         
      },
      {
        deep: true,
        immediate: false
      }
    )
      
    expose({
      refresh,
      reset,
      loadList
    })
    return () => {
      return (
        <div class="ylui-table" v-loading={loading.value}>
           <div class="ylui-table__content">
            <el-table
              v-slots={{
                empty: () => <el-empty description="暂无数据" />
              }}
              data={tableData.value}
              {...attrs}
              ref = {domRef}
              height="100%"
              onSelectAll={selectFn}
              onSelectionChange= { selectFn}
            >
              {renderLeftColumns()}
              {tableModal && renderColumns()}
              {renderRightActions()}
            </el-table>
          </div>
          {
            (customerProps.showCheck || customerProps.showPagination) && 
            <div class="ylui-table__footer">
            
            { customerProps.showCheck  &&  <el-button type="default" onClick={allFn} plain >全选
           </el-button>}             
           {customerProps.showCheck &&all.value.length>0 && <el-button type="default" onClick={clearFn} plain >清空(已{all.value.length}选)
           </el-button>   } 
            <div class="ylwl_customerFooterTips">
              {slots.leftFooter && slots.leftFooter()}
            </div>
            <div style="flex:1"></div>
            {
              customerProps.showPagination &&  <el-pagination
              background
              page-sizes={[10, 20, 50, 100]}
               v-model:page-size={pagination.size}
               v-model:current-page={pagination.page}
              layout="prev, pager, next,total,sizes"

              total={count.value}
              {...customerProps.pagination} 
         
            />
            }
           
        </div>

          }
        
        </div>
      )
    }
  }
})
